package com.kehongborui.fliggy.interceptor;

import com.kehongborui.fliggy.controller.TestController;
import com.kehongborui.fliggy.exception.AuthenticationException;
import com.kehongborui.fliggy.exception.FliggyException;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-08-30
 */
public class FliggyHandlerExceptionResolver implements HandlerExceptionResolver {
    private Logger log = Logger.getLogger(FliggyHandlerExceptionResolver.class);
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Object handler, Exception ex) {
        if (ex instanceof FliggyException) {
            request.setAttribute("code", 500);
            request.setAttribute("err_msg", ex.getMessage());
        }

        if (ex instanceof AuthenticationException) {
            request.setAttribute("code", ((AuthenticationException) ex).getMsg().getCode());
            request.setAttribute("err_msg", ex.getMessage());
            request.setAttribute("redirectURL", "/login");
            return new ModelAndView("common/nopower");
        }

        if (ex instanceof  NullPointerException) {
            request.setAttribute("code", 500);
            request.setAttribute("err_msg", ex.getMessage());
        }

        log.error(ex.getLocalizedMessage());
        ex.printStackTrace();
        return new ModelAndView("common/error");
    }
}
